package by.bsuir.chess.models
{
	import by.bsuir.chess.events.PiecePositionEvent;
	import by.bsuir.chess.vo.Piece;

	import mx.collections.ArrayCollection;

	[Bindable]
	public class GameModel
	{
		//2-dimensional array of pieces
		private var _boardState : Array;
		private var _pieces : ArrayCollection;

		public function GameModel(lock : SingletonLock)
		{
		}

		public function get boardState() : Array
		{
			return _boardState;
		}

		public function set boardState(value : Array) : void
		{
			_boardState = value;
			var piece : Piece;
			for(var i : int = 1; i <= 8; i++)
				for(var j : int = 1; j <= 8; j++)
				{
					piece = _boardState[i][j];
					if(piece)
						piece.addEventListener(PiecePositionEvent.POSITION_CHANGE, onPiecePositionChange);
					_pieces.addItem(piece);
				}
		}

		private function onPiecePositionChange(event : PiecePositionEvent) : void
		{
			_boardState[event.oldPos.x][event.newPos.y] = null;
			_boardState[event.newPos.x][event.newPos.y] = event.target;
		}

		public function get pieces() : ArrayCollection
		{
			return _pieces;
		}

		public function getKing(color : int) : Piece
		{
			for each (var piece : Piece in pieces)
				if(piece.type == Piece.KING && piece.color == color)
					return piece;
			return null;
		}

		private static var _inst : GameModel;

		public static function get inst() : GameModel
		{
			if(!_inst)
				_inst = new GameModel(new SingletonLock());
			return _inst;
		}
	}
}
class SingletonLock
{

}
